package com.example.wangning.mycarofcountry.tool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by dllo on 15/12/15.
 * 圆形图
 */
public class CirCle extends ImageView{
    public CirCle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CirCle(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //获得imageView里存的图片
        Drawable drawable = getDrawable();
        Paint paint = new Paint();
        if (drawable != null){
            //将图片处理为圆形
            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();//获得drawable里的图片
            Bitmap b = getCircleBitmap(bitmap);
            Rect rectSrc = new Rect(0,0,b.getWidth(),b.getHeight());
            Rect rectDest = new Rect(0,0,getWidth(),getHeight());
            canvas.drawBitmap(b,rectSrc,rectDest,paint);
        }else {
            //没给图片不处理，用默认的方法
            super.onDraw(canvas);
        }

    }
    //获取 圆形的Bitmap
    private Bitmap getCircleBitmap(Bitmap bitmap){
        Bitmap outPut = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas();
        canvas.setBitmap(outPut);//让画布画出的图像，显示在outPut这张bitmap上
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        //矩形范围是bitmap
        Rect rect = new Rect(0,0,bitmap.getHeight(),bitmap.getWidth());
        canvas.drawCircle(bitmap.getHeight()/2,bitmap.getHeight()/2,bitmap.getHeight()/2,paint);
        //设置叠放方式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap,rect,rect,paint);
        return outPut;
    }
}
